import { login, logout, getInfo } from '@/api/user';
import { getToken, setToken, removeToken } from '@/utils/auth';
import { resetRouter } from '@/router';
import {
  USER_RESET_STATE,
  USER_SET_TOKEN,
  USER_SET_NAME,
  USER_SET_AVATAR
} from '../../const/mutationTypes';

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  };
};

const state = getDefaultState();

const mutations = {
  [USER_RESET_STATE]: (state) => {
    Object.assign(state, getDefaultState());
  },
  [USER_SET_TOKEN]: (state, token) => {
    state.token = token;
  },
  [USER_SET_NAME]: (state, name) => {
    state.name = name;
  },
  [USER_SET_AVATAR]: (state, avatar) => {
    state.avatar = avatar;
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password })
        .then((response) => {
          const { data } = response;
          commit(USER_SET_TOKEN, data.token);
          setToken(data.token);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          const { data } = response;

          if (!data) {
            return reject(new Error('Verification failed, please Login again.'));
          }

          const { name, avatar } = data;

          commit(USER_SET_NAME, name);
          commit(USER_SET_AVATAR, avatar);
          return resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit(USER_RESET_STATE);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit(USER_RESET_STATE);
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
